/*
 * Copyright (C) 2009 - 2010 Plausible Labs Cooperative, Inc.
 * All rights reserved.
 *
 * Permission is hereby granted, free of charge,
 * to any person obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to permit
 * persons to whom the Software is furnished to do so, subject to the following
 * conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#import "Block.h"
#import "PLBlockConcrete.h"

#import <CoreFoundation/CoreFoundation.h>
#import <objc/runtime.h>

class Example {
    public:
    
    int value;
    
    explicit Example (int value) : value(value) {}
};

/**
 * Verify that C++ stack and global blocks correctly link and run.
 *
 * @param error If an error occurs, the argument will be set to the
 * error description.
 */
extern "C" boolean_t BlockCPPTests (CFStringRef *error) {
    /* Test global block ABI */
    int (^Global)() = ^{
        return 42;
    };
    void *global = Global;
    
    if (object_getClass((id)global) != (Class) objc_getClass("_PLGlobalBlock") && 
        object_getClass((id)global) != (Class) &_PLConcreteGlobalBlock2)
    {
        CFShow(Global);
        *error = CFSTR("Global block has unexpected isa");
        return false;
    }
    
    if (Global() != 42) {
        *error = CFSTR("Global block returned expected value");
        return false;
    }
    
    /* Test stack block ABI, including C++ const copy capture */
    Example captured = Example(42);
    int (^Stack)() = ^{
        return captured.value;
    };
    void *stack = Stack;
    
    if (object_getClass((id)stack) != (Class) objc_getClass("_PLStackBlock") && 
        object_getClass((id)stack) != (Class) &_PLConcreteStackBlock2)
    {
        CFShow(stack);
        *error = CFSTR("Stack block has unexpected isa");
        return false;
    }
    
    if (Stack() != 42) {
        *error = CFSTR("Stack block returned expected value");
        return false;
    }

    /* Test handling of C++ block copy */
    int (^Copy)() = (int (^)()) Block_copy(Stack);
    if (Copy() != 42) {
        *error = CFSTR("Heap block returned expected value");
        return false;
    }
    Block_release(Copy);
    
    /* All passed */
    return true;
}
